<template>
  <div class="data" ref="dataBody">

    <div class="data-menu">
      <div class="scroll-bar">
        <div class="menu-container">
          <g-menu-item v-for="item in menu" :data="item" :selected="selected" :key="item.name" @on-select="selectDataType" :groupDataChilds="groupDataChilds" :deptDataChilds="deptDataChilds"></g-menu-item>

          <div class="menu-button-wrap">
            <div class="button-word" @click="addBookmark">
              添加收藏夹
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="data-body">

      <transition name="fade" v-if="loading">
        <div class="content-loading" v-show="loading">
          <div class="conent-loading-animate">
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>
      </transition>

      <div class="data-body-content">
        <keep-alive>
          <router-view v-if="dataTypes.includes(selected) || bookmarksGeted" @on-view-load="onLoad" v-on:data-store="dataStore" v-on:move-out-store="moveOutStore" v-on:remove-bookmark="removeBookmark" v-on:rename="bookmarkRename" v-on:change-loading="changeLoading" :bookmarks="bookmarks" :orgUid="orgUid"></router-view>
        </keep-alive>
      </div>
    </div>

    <transition-group name="fade">
      <data-store v-if="openStore" key='store' :storeData="storeData" :bookMarks="bookmarks" :dataType="selected" v-on:store-result="storeResult" v-on:close-store="closeStore"></data-store>
    </transition-group>
  </div>
</template>

<script>
import Bus from "@/utils/event_bus";
import GMenuItem from "@/components/common/g-menu-item";
import DataStore from "@/components/data/data-store";
import { bookmark as bookmarkAPI, cloudData as cloudDataAPI } from "@/api";
import newConfig from "@/config/newConfig.js";
import { tianjing as tianjingAPI } from "@/api";

const menu = [
  {
    name: "数据",
    type: "data",
    submenu: [
      {
        name: "个人资源",
        key: "private-data",
        icon: "my-data",
        show: "basic_personal_data",
        count: 0
      },
      {
        name: "公共资源",
        key: "public-data",
        icon: "public-data",
        show: "basic_public_data",
        count: 0
      }
      // {
      //   name: '群组资源',
      //   key: 'group-data',
      //   icon: 'public-data',
      //   show: 'basic_group_data',
      //   count: 0
      // },
      // {
      //   name: '部门资源',
      //   key: 'dept-data',
      //   icon: 'public-data',
      //   show: 'basic_dept_data',
      //   count: 0
      // },
      // {
      //   name: '注册资源',
      //   key: 'reg-data',
      //   icon: 'public-data',
      //   show: 'basic_reg_data',
      //   count: 0
      // }
      // {
      // 	name: '公共影像',
      // 	key: 'public-imagery',
      // 	icon: 'my-data',
      // 	show: 'basic_public-imagery',
      // 	count: 0
      // },
      // {
      // 	name: '群组数据',
      // 	key: 'group-data',
      // 	icon: 'group-data',
      // 	show: 'basic_group_data',
      // 	count: 0
      // }
    ]
  },
  {
    name: "收藏夹",
    type: "bookmark",
    submenu: []
  }
];

let loadingHandler;

export default {
  name: "data-index",

  components: {
    GMenuItem,
    DataStore
  },

  data() {
    return {
      menu,
      orgUid: this.$root.org.orgUid,
      selected: "",
      loading: true,
      currentMenu: "",
      waiting: false,
      openStore: false,
      storeData: "",
      bookmarks: [],
      bookmarksGeted: false,
      loading: false,
      loaded: [],
      dataTypes: [
        "private-data",
        "public-data",
        "group-data",
        "resgroup-data",
        "dept-data",
        "reg-data",
        "public-imagery"
      ],
      groupDataChilds: [],
      deptDataChilds: []
    };
  },

  async mounted() {
    this.setSelected();
    await this.getSummary();
    await this.getBookmarks();
    // await this.initChildData();

    Bus.$on("upload-success", () => {
      this.countChange("private-data", "plus");
    });

    Bus.$on("geofile-upload-success", () => {
      this.countChange("private-data", "plus");
    });

    Bus.$on("summary-reset", () => {
      this.getSummary();
    });

    Bus.$on("clear-bookmark-count", () => {
      this.getBookmarks();
    });
  },
  activated() {
    let selected = this.selected;
    this.$store.state.data_nav_key = selected;

    if (selected) {
      if (this.dataTypes.includes(selected)) {
        this.$router.push({
          path: "/data/" + selected
        });
      } else {
        this.$router.push({
          name: "StarData",
          params: {
            bookmarkUid: selected
          }
        });
      }
    }

    this.$emit("on-view-load");
  },

  methods: {
    setSelected() {
      let path = this.$router.currentRoute.path;
      let paths = path.split("/");
      this.selected =
        paths[2] === "bookmark" ? paths[3] : paths[2] || "private-data";

      // Bus.$emit('on-submenu-change', '我的数据');
    },

    //初始化节点
    async initChildData() {
      //初始化群组节点
      let groupData = await tianjingAPI.userGroup();
      if (!groupData || !groupData.data.data) return;

      this.groupDataChilds = groupData.data.data;

      //初始化部门节点
      let deptData = await tianjingAPI.userDept();
      if (!deptData || !deptData.data.data) return;
      //递归求节点
      function getChildaArray(data, that) {
        for (let val of data) {
          that.deptDataChilds.push(val);
          if (!val.children) break;
          getChildaArray(val.children, that);
        }
      }
      getChildaArray(deptData.data.data, this);

      console.log(this.groupDataChilds, this.deptDataChilds);
    },

    async selectDataType(key) {
      // console.log(key);
      this.$store.state.data_nav_key = key;
      if (key === this.selected) return;
      this.selected = key;

      if (this.dataTypes.includes(key)) {
        this.$router.push({
          path: "/data/" + key
        });
      } else {
        this.$router.push({
          name: "StarData",
          params: {
            bookmarkUid: key
          }
        });
      }

      if (this.loaded.includes(key)) {
        this.loading = false;
      } else {
        // this.loaded.push(key);
        this.loading = true;
      }
    },

    async getSummary() {
      let result = await cloudDataAPI.summary();
      //let result_2 = await cloudDataAPI.summary_2();

      if (result.data.code != 0) {
        this.$message.error("获取数据列表出错");
        return;
      }
      //if (result_2.data.code != 0) {
      //  this.$message.error("获取数据列表出错");
      //  return;
      //}
      let data = {};
      // data.regData = data.publicData;
      data.data = result.data.data.data;
      data.publicData = result.data.data.publicData;

      //let data_2 = result_2.data.data;
      //data.regData = data_2.publicData;

      let menu = this.menu[0].submenu;

      let mapping = {
        "private-data": "data",
        "public-data": "publicData",
        "group-data": "groupData",
        "dept-data": "deptData",
        "reg-data": "regData",
        "public-imagery": "publicImagery"
      };

      let summary = [];

      menu.forEach((n, index) => {
        let key = n.key;
        let val = mapping[key];

        if (typeof data[val] === "number") {
          n.count = Number(data[val]);
          summary.push(n);
        }
      });

      /*

      let url = `${newConfig.api}/resourceReg/query/count`;
      this.$root.$http.get(url).then(response => {


        let resource = response.data.data.resource;
        for (let index in resource) {
          let item = resource[index];
          if (item.code == "0") {
            //公共资源
            data.publicData = item.count;
          } else if (item.code == "1") {
            //部门资源
            data.deptData = item.count;
          } else if (item.code == "2") {
            //群组资源
            data.groupData = item.count;
          } else if (item.code == "3") {
            //个人资源
            data.data = data_2.data + item.applyCount;
          }
        }

        let mapping = {
          "private-data": "data",
          "public-data": "publicData",
          "group-data": "groupData",
          "dept-data": "deptData",
          "reg-data": "regData",
          "public-imagery": "publicImagery"
        };

        let summary = [];

        menu.forEach((n, index) => {
          let key = n.key;
          let val = mapping[key];

          if (typeof data[val] === "number") {
            n.count = Number(data[val]);
            summary.push(n);
          }
        });
      });
      */
    },
    handleChildLeaf(data) {
      //群组子节点
      // let groupList = data.group;
      // this.groupDataChilds = [];
      // groupList.forEach(item => {
      //   this.groupDataChilds.push({
      //     groupId: item.code,
      //     groupName: item.name,
      //     count: item.count
      //   });
      // });
      //部门子节点
      let deptList = data.dept;
      this.deptDataChilds = [];
      //递归求节点
      function getChildaArray(data, that) {
        that.deptDataChilds.push({
          id: data.id,
          label: data.label,
          count: data.count
        });
        let children = data.children;
        if (children) {
          for (let item of children) {
            getChildaArray(item, that);
          }
        }
      }
      getChildaArray(deptList[1], this);
      // console.log(this.deptDataChilds);
    },
    async getBookmarks() {
      let result = await bookmarkAPI.list();

      if (result.data.code != 0) {
        this.$message.error("获取收藏夹列表失败");
        return;
      }

      let bookmarks = result.data.data;

      // let menu = this.menu[1].submenu;

      let menu = [];

      bookmarks.forEach(n => {
        menu.push({
          name: n.name,
          key: n.uid,
          icon: "project",
          activeIcon: "project-active",
          count: n.count
        });
      });
      this.bookmarksGeted = true;
      this.menu[1].submenu = this.bookmarks = menu;
    },

    addBookmark() {
      if (this.waiting) return;

      if (this.bookmarks.length > 10) {
        this.$message.warning("您最多可建10个收藏夹");
        return;
      }

      let inputPattern = /^[\u4E00-\u9FA5_A-Za-z0-9-（）()]{2,20}$/;

      let promise = this.$prompt(" ", "新建收藏夹", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "输入收藏夹名称，2-20个汉字、字母、数字",
        startWaiting: instance => {
          instance.editorErrorMessage = null;
          instance.$refs.input.classList.remove("invalid");

          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "操作中...";
          instance.cancelButtonDisabled = true;
        },
        stopWaiting: instance => {
          instance.confirmButtonLoading = false;
          instance.confirmButtonText = "确定";
          instance.cancelButtonDisabled = false;
        },
        beforeClose: async (action, instance, done) => {
          let result = "";

          if (action === "confirm") {
            let inputValue = instance.inputValue;

            if (inputValue.length > 20 || inputValue.length < 2) {
              instance.editorErrorMessage =
                "收藏夹名称应当为2-20个汉字、字母或数字";
              instance.$refs.input.classList.add("invalid");
              return;
            }

            let ok = inputPattern.test(inputValue);

            if (!ok) {
              instance.editorErrorMessage = "收藏夹名称包含非法字符";
              instance.$refs.input.classList.add("invalid");
              return;
            }

            instance.startWaiting(instance);

            this.waiting = true;

            if (inputValue) {
              let menu = this.menu;
              let bookmarks = menu[1].submenu;

              result = await bookmarkAPI.create({
                name: inputValue
              });

              if (!result) {
                this.$message.error("新建收藏夹失败");
                this.waiting = false;
                instance.stopWaiting(instance);
                done();
                return;
              }

              if (result && result.data.code === 613) {
                instance.editorErrorMessage = "收藏夹名称已被使用";
                instance.$refs.input.classList.add("invalid");
                this.waiting = false;
                instance.stopWaiting(instance);
                return;
              }

              if (result.data.code != 0) {
                this.$message.error("新建收藏夹失败");
                this.waiting = false;
                instance.stopWaiting(instance);
                done();
                return;
              }

              let data = result.data.data;

              bookmarks.push({
                name: inputValue,
                key: data.uid,
                icon: "project",
                activeIcon: "project-active",
                count: 0
              });
            }

            this.waiting = false;
            this.$message.success("新建收藏夹成功");
            done();
            instance.confirmButtonLoading = false;
          } else {
            done();
            this.waiting = false;
          }
        }
      });

      promise.then(async ({ value }) => {}).catch(() => {});
    },

    bookmarkRename(uid, name) {
      this.bookmarks.forEach(n => {
        if (n.key === uid) {
          n.name = name;
        }
      });
    },

    removeBookmark(bookmarkUid) {
      this.bookmarks.forEach((n, index) => {
        if (n.key == bookmarkUid) {
          this.bookmarks.splice(index, 1);
          this.selected = "private-data";
        }
      });
    },

    onLoad() {
      clearTimeout(loadingHandler);
    },

    dataStore(data) {
      if (!this.bookmarks.length) {
        this.$message.warning("未找到收藏夹，请点击添加收藏夹新建");
        return;
      }

      this.storeData = data;
      this.openStore = true;
    },

    closeStore() {
      this.storeData = "";
      this.openStore = false;
    },

    storeResult(result) {
      let code = result.code;

      if (code === 701) {
        this.$message.error("该分享数据已被删除");
        return;
      }

      let bookmarkUid = result.bookmarkUid;
      let msg = bookmarkUid
        ? bookmarkUid.length
          ? "收藏"
          : "取消收藏"
        : "操作";

      if (code != 0) {
        this.$message.error(msg + "失败");
        return;
      }

      this.closeStore();

      this.$message.success(msg + "成功");

      Bus.$emit("clear-bookmark-data", bookmarkUid);

      this.getBookmarks();
    },

    moveOutStore() {
      let bookmarkUid = this.selected;
      this.countChange(bookmarkUid, "minus");
    },

    countChange(key, type) {
      let menu = this.menu;
      menu = this.dataTypes.includes(key) ? menu[0].submenu : menu[1].submenu;

      menu.forEach((n, index) => {
        if (key === n.key) {
          let count = n.count;
          n.count = type === "plus" ? count + 1 : count - 1;
        }
      });
    },

    changeLoading(obj) {
      this.$data.loading = false;

      if (this.loaded.includes(obj.key)) {
        return;
      } else {
        if (obj.add) {
          this.loaded.push(obj.key);
        }
      }
    }
  }
};
</script>

<style lang="scss">
@import "common";

@function delay($interval, $count, $index) {
  @return ($index * $interval) - ($interval * $count);
}

@mixin ball-pulse-sync($n: 3, $start: 1) {
  @for $i from $start through $n {
    > div:nth-child(#{$i}) {
      animation: ball-pulse-sync 0.6s delay(0.07s, $n, $i) infinite ease-in-out;
    }
  }
}

.data {
  height: 100%;
  overflow: hidden;

  .data-menu {
    float: left;
    height: 100%;
    width: 180px;
    // border-right: 1px solid #ccc;
    overflow: hidden;

    .menu-button-wrap {
      padding-top: 20px;

      .button-word {
        height: 30px;
        line-height: 28px;
        width: 120px;
        border-radius: 3px;
        border: 1px solid $primary;
        color: $primary;
        text-align: center;
        margin: 0 auto;
        cursor: pointer;

        &:hover {
          border: 1px solid $darkPrimary;
          color: $darkPrimary;
          font-weight: 500;
        }
      }
    }
  }

  .data-body {
    height: 100%;
    overflow: hidden;
    position: relative;

    .content-loading {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1000;
      width: 100%;
      height: 100%;
      background: $bgWhite;
      opacity: 1;

      .conent-loading-animate {
        width: 200px;
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -120px;
        margin-left: -100px;
        text-align: center;
        line-height: 200px;
        @include ball-pulse-sync();

        > div {
          width: 15px;
          height: 15px;
          background-color: $primary;
          border-radius: 100%;
          margin: 5px;
          display: inline-block;
        }
      }

      &.fade-leave-active {
        opacity: 0;
        transition: opacity 0.3s;
      }
    }

    .data-body-content {
      width: 100%;
      height: 100%;

      .adaption {
        margin: 0 auto;

        @media screen and (min-width: 1741px) {
          max-width: 1320px;
        }

        @media screen and (max-width: 1740px) {
          max-width: 1050px;
        }

        @media screen and (max-width: 1560px) {
          max-width: 780px;
        }

        @media screen and (max-width: 1200px) {
          max-width: 510px;
        }

        @media screen and (max-width: 900px) {
          max-width: 240px;
        }
      }

      .adaption-list {
        // overflow-x: hidden;
        margin: 0 auto;
        max-width: 1320px;
        min-width: 510px;

        ul {
          overflow: inherit !important;
        }

        @media screen and (min-width: 1740px) {
          max-width: 1320px;
        }

        @media screen and (max-width: 1740px) {
          max-width: 1050px;
        }

        @media screen and (max-width: 1560px) {
          max-width: 780px;
        }

        @media screen and (max-width: 1200px) {
          max-width: 510px;
        }
      }

      .data-list-container {
        padding: 68px 0 64px 0;
        height: 100%;

        .no-data {
          text-align: center;
          // padding: 50px 0;
          position: absolute;
          width: 100%;
          top: 50%;
          transform: translate(0, -100%);
          @include user-select(none);

          .no-data-tip {
            margin-top: 16px;
            font-size: 14px;
            color: $gray;
          }

          .empty-handler {
            height: 30px;
            line-height: 28px;
            width: 72px;
            border-radius: 3px;
            color: $white;
            text-align: center;
            margin: 16px auto 0 auto;
            background-color: $primary;
            cursor: pointer;

            &:hover {
              background-color: $darkPrimary;
              font-weight: 500;
            }
          }
        }

        .wrapper-body {
          height: 100%;

          .list-view-header {
            height: 50px;
            padding: 8px 0;
            line-height: 32px;
            font-size: 14px;
            color: $gray;
            border-top: 1px solid $bdGray;
            border-bottom: 1px solid $bdGray;

            > div {
              float: left;
              height: 100%;
            }

            .name {
              width: 35%;
              padding: 0 4px;
              text-align: left;
              @include text-overflow();
            }

            .data-count {
              width: 10%;
              text-align: right;
            }

            .date {
              width: 25%;
              text-align: right;
            }

            .data-option {
              width: 30%;
              text-align: center;
            }
          }

          .data-vertical-scroll {
            width: 100%;
            height: 100%;

            &.with-header {
              height: calc(100% - 50px);
            }

            .g-scrollbar-scrollbar-vertical {
              width: 10px;
            }

            .scrollbar {
              display: block !important;
              width: 10px;
              background-color: #9e9e9e;
            }

            .scrollbar.g-scrollbar-transition {
              width: 10px;
            }
          }

          .datas-content {
            margin: 0 -15px;

            .data-view {
              overflow: hidden;
            }
          }

          .add-more-wrapper {
            width: 88px;
            height: 26px;
            margin: 36px auto;

            .add-more {
              cursor: pointer;
              border-radius: 12px;
              color: $gray;
              font-size: 12px;
              line-height: 22px;
              margin: auto;
              text-align: center;
              white-space: nowrap;
              vertical-align: middle;
              width: 86px;
              height: 24px;
              border: 1px solid $bdGray;
              background-color: transparent;

              i {
                font-size: 12px;
              }

              &:hover {
                border: 1px solid darker($bdGray, 10%);
              }
            }
          }
        }
      }
    }
  }
}
.g-menu-item .g-submenu .g-submenu-item .submenu-item-active {
  background: #4087f7 !important;
}
</style>
